﻿using B.T.Smark.APIRead.Applications.Command;
using B.T.Smark.Domain;
using B.T.Smark.ErrorCode;
using B.T.Smark.Infartructrue.Interfaces;
using MediatR;

namespace B.T.Smark.APIRead.Applications.CommandHandler
{
    public class UserDelCommandHandler : IRequestHandler<UserDelCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserInfor> userRepository;

        public UserDelCommandHandler(IBaseRepository<UserInfor> userRepository)
        {
            this.userRepository = userRepository;
        }

        public Task<APIResult<int>> Handle(UserDelCommand request, CancellationToken cancellationToken)
        {
           //批量删除
            if (request.Id != null && request.Id.Count > 0)
            {
                foreach (var userId in request.Id)
                {
                    var user = userRepository.GetAll(userId);
                    if (user == null)
                    {
                        return Task.FromResult(APIResult<int>.Fail(ErrorCode.UserNotFound));
                    }
                    userRepository.Delete(user);
                }
                return Task.FromResult(APIResult<int>.Success(request.UserIds.Count));
            }
            //单个删除
            else
            {
                var user = userRepository.GetById(request.Id);
                if (user == null)
                {
                    return Task.FromResult(APIResult<int>.Fail(ErrorCode.UserNotFound));
                }
                userRepository.Delete(user);
                return Task.FromResult(APIResult<int>.Success(1));
            }


        }
    }
}
